import Pager from '@/components/comp/Pager';
import ParseFileUtil from '@/components/util/parseFile.js';
import DataTypeUtil from '@/components/util/dataTypeUtil.js';
import ExportUtil from '@/components/util/exportUtil.js';
import CalcUtil from '@/components/util/calcUtil.js';
import DataSourceUtil from '@/components/util/dataSourceUtil.js';
import DataTable from '@/components/comp/DataTable';
export default {
  name: 'DataSource',
  props: {
    langType: {
      type: String,
      default: window.localStorage.getItem('langType'),
    },
  },
  components: {
    pager: Pager,
    'data-table': DataTable,
  },
  data: () => ({
    label: {
      dataWay: { zh: '数据方式', en: 'Data Way' },
      dataAttributes: { zh: '数据属性', en: 'Data Attributes' },
      dataCalc: { zh: '数据计算', en: 'Data Calculate' },
      upload: { zh: '上传文件', en: 'Upload File' },
      parse: { zh: '解析', en: 'PARSE' },
      host: { zh: '地址', en: 'host' },
      port: { zh: '端口', en: 'port' },
      query: { zh: '查询', en: 'query' },
      database: { zh: '数据库', en: 'database' },
      table: { zh: '表格', en: 'table' },
      userName: { zh: '账号', en: 'loginNo' },
      pwd: { zh: '密码', en: 'password' },
      connect: { zh: '连接', en: 'CONNECT' },
      request: { zh: '请求', en: 'REQUEST' },
      paramName: { zh: '参数名', en: 'paramName' },
      paramValue: { zh: '参数值', en: 'paramValue' },
      addParam: { zh: '添加参数', en: 'ADD PARAM' },
      addTable: { zh: '添加到表格', en: 'ADD TO Table' },
      detail: { zh: '数据包描述', en: 'description' },
      title: { zh: '数据包名称', en: 'title' },
      titleError: { zh: '请填写至少两个字的名称', en: 'Please input name of at least 2 words' },
      sourceId: { zh: '数据包ID', en: 'SOURCE ID' },
      code: { zh: '代码', en: 'code' },
      name: { zh: '名称', en: 'name' },
      type: { zh: '类型', en: 'type' },
      calc: { zh: '计算', en: 'calc' },
      updateTable: { zh: '更新表格', en: 'UPDATE TABLE' },
      nodata: { zh: '暂无数据', en: 'NO DATA' },
      nofile: { zh: '请上传数据文件!', en: 'Please upload data file!' },
      errorFile: {
        zh: '请上传正确格式的数据文件！',
        en: 'Please upload the data file in the correct format!',
      },
      create: { zh: '新建', en: 'CREATE' },
      save: { zh: '保存', en: 'SAVE' },
      saveFail: { zh: '保存数据包失败！', en: 'Fail to save data package!' },
      saveOK: { zh: '保存数据包成功！', en: 'Succeed to save data package!' },
      update: { zh: '更新', en: 'UPDATE' },
      updateFail: { zh: '更新数据包失败!', en: 'Fail to update data package!' },
      updateOK: { zh: '更新数据包成功!', en: 'Succeed to update data package!' },
      export: { zh: '导出', en: 'EXPORT' },
      exitFullscreen: { zh: '退出全屏', en: 'EXIT FULL SCREEN' },
      fullScreen: { zh: '全屏', en: 'FULL SCREEN' },
      resetParam: { zh: '重置参数', en: 'RESET PARAM' },
      repeatParam: { zh: '存在重复参数', en: 'REPEATED PARAM' },
      dataTable: { zh: '数据表格', en: 'Data Table' },
      dataNum: { zh: '数据项数量:', en: 'number of items:' },
      originData: { zh: '原始数据', en: 'Origin Data' },
      calcData: { zh: '计算数据', en: 'Calc Data' },
      loadDataFail:{zh:"加载数据失败!",en:"Fail to load data!"},
      requestTip: { zh: '请求数据失败!', en: 'Fail to request data!' },
      mysqlTip: { zh: '获取MySQL数据库数失败!', en: 'Fail to get data from MySQL database' },
      calcOver: {
        zh: '最多选择两个参数进行计算',
        en: 'Select at most two parameters for calculation',
      },
      calcTip: {
        zh:
          '请设置一个计算参数为类目，计算类型为原始数据，设置另一个计算参数为数值，计算类型为除原始数据外的计算',
        en: 'Please set one param as category with origin and the other as value width other calc',
      },
      calcTip1: {
        zh: '选中一个参数计算类型只能为计数',
        en: 'Selected one param only can be count',
      },
    },
    //数据方式
    dataType: [
      { name: 'EXCEL', icon: 'iconexcel' },
      { name: 'CSV', icon: 'iconCSV' },
      { name: 'JSON', icon: 'iconjson' },
      { name: 'MySQL', icon: 'iconmysql' },
      { name: 'URL', icon: 'iconlink' },
      { name: 'Custom', icon: 'iconPencil' },
    ],
    //选中数据方式
    selectDataWay: 0,
    //上传文件名
    uploadFile: '',
    //上传需解析文件
    parseFile: null,
    //上传文件错误提示 0=》无错误 1=》未上传文件  2=》上传文件格式错误
    uploadError: 0,
    //mysql查询内容选择 true=》sql  false=》table
    switchQuery: false,
    //获取mysql数据库数据
    mySQLSet: {
      host: '',
      port: '',
      user: '',
      pwd: '',
      database: '',
      query: 'table',
      table: '',
      sql: '',
    },
    //通过url获取对应的数据
    urlSet: {
      url: '',
      params: [{ name: '', val: '' }],
    },
    //是否第一次添加自定义数据
    isAddCustom: false,
    //自定义数据
    customTable: [{ name: '', val: '' }],
    //数据包设置
    packageSet: {
      sourceId: '',
      title: '',
      detail: '',
    },
    //数据类型
    types: ['string', 'number', 'date', 'datetime', 'boolean'],
    //表格数据
    dataList: [],
    //显示的表格数据
    dataListShow: [],
    //表格数据属性
    dataAttr: [],
    //选中计算属性
    dataCalc: [],
    //选中显示属性
    selectedAttrData: [],
    //计算属性类型
    paramType: [
      { zh: '类目', en: 'category' },
      { zh: '数值', en: 'value' },
      // { zh: '时间', en: 'time' },
    ],
    //属性进行的属性
    calcType: [
      { zh: '原始数据', en: 'origin' },
      { zh: '求和', en: 'sum' },
      { zh: '计数', en: 'count' },
      { zh: '平均', en: 'average' },
      { zh: '最大', en: 'max' },
      { zh: '最小', en: 'min' },
    ],
    //分页器设置
    pagerCurrent: 1,
    pagerTotal: 1,
    pagerLimit: 20,
    //数据表格设置
    tableH: 'calc(100% - 57px)',
    tableW: '100%',
    //选中表格项
    selectDataTable: -1,
    //全屏
    isFullscreen: false,
    //自定义数据参数重复
    isCustomRepeat: false,
    //url参数重复
    isUrlRepeat: false,
    //原始数据
    originDataList: '',
    //是否显示计算表格
    isTableCalc: false,
    //计算结果
    calcList: [],
    //计算结果属性
    calcAttr: [
      { name: 'name', code: 'name', type: 'string' },
      { name: 'value', code: 'value', type: 'number' },
    ],
    //选中计算结果项
    selectedCalcData: [],
    //计算参数个数是否超
    isCalcOver: false,
    //计算参数设置是否错误
    isCalcParam: false,
    isCalcParam1: false,
    //是否显示提示alertdialog
    isAlert: false,
    alertTip: '',
   
    isDataInfo: false,
    listHeight:"600px"
  }),
  watch:{
    selectedCalcData(){

    }
  },

  methods: {
    //创建新的数据表格
    newDataTable() {
      this.packageSet = {
        sourceId: '',
        title: '',
        detail: '',
      };
      this.dataList = [];
      this.dataAttr = [];
      this.calcList = [];
      this.calcAttr = [];
      this.selectedCalcData = [];
      this.selectDataTable = [];
      window.location.hash = '#/datasource';
    },
    //连接数据库并获取数据
    connectMySQL() {
      var that = this;
      DataSourceUtil.connectMySQL(this.mySQLSet, {}, function(data) {
        if (data.dataList) {
          that.dataList = data.dataList;
          that.loadAttrList();
        } else {
          that.alertTip = that.getLangText(that.label.mysqlTip);
          that.isAlert = true;
        }
      });
    },
    //请求api并获取数据
    doRequest() {
      if (!this.checkTableParam(this.urlSet.params)) {
        this.isUrlRepeat = true;
        return;
      }
      this.isUrlRepeat = false;

      var that = this;
      DataSourceUtil.doRequest(this.urlSet, {}, function(data) {
        if (data.dataList) {
          that.dataList = data.dataList;
          that.loadAttrList();
        } else {
          that.alertTip = that.getLangText(that.label.requestTip);
          that.isAlert = true;
        }
      });
    },
    //导出表格数据
    exportDataTable() {
      ExportUtil.exportTable1(this.selectedAttrData, this.dataList);
    },
    getDataSourceJSON() {
      this.updateTableType();
      var list = [],
        attr = [];
      if (!this.isTableCalc) {
        for (var i = 0; i < this.dataList.length; i++) {
          var item = {};
          for (var j = 0; j < this.selectedAttrData.length; j++) {
            item[this.selectedAttrData[j].code] = this.dataList[i][this.selectedAttrData[j].code];
          }
          list.push(item);
        }
        attr = this.selectedAttrData;
      } else {
        list = this.calcList;
        attr = this.calcAttr;
        this.selectDataWay = 0;
      }
      return { list, attr };
    },
    getPostData() {
      
      
      var result = this.getDataSourceJSON();
      console.log(result);
      var data = {
        userId: JSON.parse(window.localStorage.getItem("carweb_user")).userId,
        title: encodeURI(this.packageSet.title),
        detail: encodeURI(this.packageSet.detail),
        dataOp: encodeURI(JSON.stringify(result.attr)),
      };

      //数据包类型(1:json,2:mysql,3:url)
      var type = this.dataType[this.selectDataWay].name;
      if (type == 'MySQL') {
        data['sourceType'] = 2;
        data['param'] = encodeURI(JSON.stringify(this.mySQLSet));
      } else if (type == 'URL') {
        data['sourceType'] = 3;
        data['param'] = encodeURI(JSON.stringify(this.urlSet));
      } else {
        data['sourceType'] = 1;
        data['param'] = encodeURI(JSON.stringify(result.list));
      }
      return data;
    },
    updateDataTable() {
      if (!this.packageSet.title||this.packageSet.title.length<2) {
        this.isDataInfo = true;
        return;
      }
      var that = this;
      var data = this.getPostData();
      data['sourceId'] = this.packageSet.sourceId;
      $.post(this.API.updateDataSource, data, function(res) {
        if (res.errCode == 0) {
          //  that.packageSet.sourceId=res.data;
          that.alertTip = that.getLangText(that.label.updateOK);
          that.loadDataSource(that.packageSet.sourceId);
        } else {
          that.alertTip = that.getLangText(that.label.updateFail);
        }
        that.isAlert = true;
      });
    },
    //保存表格数据
    saveDataTable() {
      if (!this.packageSet.title||this.packageSet.title.length<2) {
        this.isDataInfo = true;
        return;
      }
      var that = this;
      var data = this.getPostData();

      $.post(this.API.saveDataSource, data, function(res) {
        if (res.errCode == 0) {
          that.packageSet.sourceId = res.data;
          that.alertTip = that.getLangText(that.label.saveOK);
          that.loadDataSource(res.data);
        } else {
          that.alertTip = that.getLangText(that.label.saveFail);
        }
        that.isAlert = true;
      });
    },
    /**全屏 */
    fullScreen() {
      var el = document.getElementById('the_datasource');

      if (!this.isFullscreen) {
        //进入全屏,多重短路表达式
        (el.requestFullscreen && el.requestFullscreen()) ||
          (el.webkitRequestFullscreen && el.webkitRequestFullscreen()) ||
          (el.mozRequestFullScreen && el.mozRequestFullScreen()) ||
          (el.msRequestFullscreen && el.msRequestFullscreen());
      } else {
        //退出全屏,三目运算符
        document.exitFullscreen
          ? document.exitFullscreen()
          : document.webkitExitFullscreen
          ? document.webkitExitFullscreen()
          : document.mozCancelFullScreen
          ? document.mozCancelFullScreen()
          : '';
      }
      this.isFullscreen = this.isFullscreen ? false : true;
      this.resizeSource();
    },
    /**上传文件结果 */
    onUploadFile(files) {
      this.parseFile = files[0];
      if (!this.parseFile) {
        this.uploadError = 1;
        return;
      }
      this.uploadError = 0;
      var ex = ParseFileUtil.getFileType(this.parseFile);
      if (ex == 'ERROR') {
        this.uploadError = 2;
      } else {
        for (var i = 0; i < this.dataType.length; i++) {
          if (this.dataType[i].name == ex) {
            this.selectDataWay = i;
            break;
          }
        }
      }
    },
    /**解析上传文件 */
    onParseFile() {
      if (!this.parseFile) {
        this.uploadError = 1;
        return;
      }
      this.uploadError = 0;
      var that = this;
      document.getElementById('wait_page').style.display='flex';
      var ex = ParseFileUtil.parseFile(this.parseFile, function(list) {
        that.dataList = list;
        that.loadAttrList();
        document.getElementById('wait_page').style.display='none';
      });
      if (ex == 'ERROR') {
        this.uploadError = 2;
      } else {
        for (var i = 0; i < this.dataType.length; i++) {
          if (this.dataType[i].name == ex) {
            this.selectDataWay = i;
            break;
          }
        }
      }
    },

    /** 获取显示表格数据*/
    getDataListShow() {
      this.dataListShow = this.dataList.slice(
        (this.pagerCurrent - 1) * this.pagerLimit,
        this.pagerCurrent * this.pagerLimit
      );
    },
    /****数据表格分页器每页数量 */
    onPagerLimit(limit) {
      this.pagerLimit = limit;
      this.pagerCurrent = 1;
      this.pagerTotal = Math.ceil(this.dataList.length / this.pagerLimit);
      this.getDataListShow();
    },
    /****数据表格分页器当前页 */
    onPagerCurrent(current) {
      this.pagerCurrent = current;
      this.getDataListShow();
    },
    /***更新表格数据类型 */
    updateTableType() {
      this.dataList = JSON.parse(this.originDataList);
      for (var i = 0; i < this.dataList.length; i++) {
        for (var j = 0; j < this.dataAttr.length; j++) {
          var val = this.dataList[i][this.dataAttr[j].code];
          var type = this.dataAttr[j].type;
          this.dataList[i][this.dataAttr[j].code] = DataTypeUtil.changeType(val, type);
        }
      }

      this.getDataListShow();
    },
    //检查计算参数
    checkCalc(){
      if ( this.selectedCalcData.length <= 2) {
        this.isCalcOver = false;
      } else {
        this.isCalcOver = true;
        return;
      }

      var category, value;
      if (this.selectedCalcData.length == 2) {
        if (this.selectedCalcData[0].type == 'category') {
          category = this.selectedCalcData[0];
          value = this.selectedCalcData[1];
        } else {
          category = this.selectedCalcData[1];
          value = this.selectedCalcData[0];
        }

        if (value.calc == 'count') {
          this.isCalcParam1 = true;
          return;
        } 
        this.isCalcParam1 = false;

        if (
          category.type != 'category' ||
          value.type != 'value' ||
          category.calc != 'origin' ||
          value.calc == 'origin'
        ) {
          this.isCalcParam = true;
          return;
        } else {
          this.isCalcParam = false;
        }
        return {category:category,value:value};
      } else if (this.selectedCalcData.length == 1) {
        category = this.selectedCalcData[0];
        if (category.calc != 'count') {
          this.isCalcParam1 = true;
          return;
        }
        this.isCalcParam1 = false;

        return {category:category,value:value};
      }
      return null;
    },
    /*** 更新表格计算结果*/
    updateTableCalc() {
     var op= this.checkCalc();
     if(!op) return;
      var xs = [],
        ys = [];
      var category=op.category, value=op.value;
      if (this.selectedCalcData.length == 2) {      

        for (var i = 0; i < this.dataList.length; i++) {
          xs.push(this.dataList[i][category.name]);
          ys.push(this.dataList[i][value.name]);
        }

        this.calcList = CalcUtil.calcData(value.calc, xs, ys);
      } else if (this.selectedCalcData.length == 1) {
        category = this.selectedCalcData[0];
        if (category.calc != 'count') {
          this.isCalcParam1 = true;
          return;
        } else {
          this.isCalcParam1 = false;
        }
        for (var i = 0; i < this.dataList.length; i++) {
          xs.push(this.dataList[i][category.name]);
        }
        this.calcList = CalcUtil.calcData('count', xs);
      }
      if (this.calcList.length > 0) {
        this.isTableCalc = true;
      }
    },
    onCalcSelect(data) {
      this.selectedCalcData = data;
     
      this.checkCalc();
    },
    /****选中属性表格数据 */
    onAttrSelect(data) {
      this.selectedAttrData = data.sort(function(a, b) {
        return CalcUtil.sortStr(a.code, b.code);
      });
    },
    /**删除自定义数据参数 */
    delCustomParm(idx) {
      if (this.customTable.length > 1 && !this.isAddCustom) {
        this.customTable.splice(idx, 1);
      }
    },
    //检测参数是否有重复
    checkTableParam(list) {
      for (var i = 0; i < list.length; i++) {
        var item = list[i];
        if (!item.name) {
          return false;
        }
        for (var j = 0; j < list.length; j++) {
          var item1 = list[j];
          if (item.name == item1.name && i != j) {
            return false;
          }
        }
      }
      return true;
    },
    /**删除自定义 */
    delUrlParm(idx) {
      if (this.urlSet.params.length > 1) {
        this.urlSet.params.splice(idx, 1);
      }
    },
    /**重置自定义表格 */
    resetCustomTable() {
      this.isAddCustom = false;
      this.dataList = [];
      this.originDataList = '';
      this.loadAttrList();
    },
    /***添加自定义数据到表格 */
    addCustomTable() {
      if (!this.checkTableParam(this.customTable)) {
        this.isCustomRepeat = true;
        return;
      }
      this.isCustomRepeat = false;
      var data = {};
      for (var i = 0; i < this.customTable.length; i++) {
        var item = this.customTable[i];
        data[item.name] = item.val;
      }
      this.dataList.push(data);
      if (!this.isAddCustom) {
        this.loadAttrList();
      } else {
        this.getDataListShow();
      }
      this.originDataList = JSON.stringify(this.dataList);
      this.isAddCustom = true;
    },
    /***添加自定义数据参数 */
    addCustomParam() {
      this.customTable.push({ name: '', val: '' });
    },
    addUrlParam() {
      this.urlSet.params.push({ name: '', val: '' });
    },
    changeDataWay(idx) {
      this.selectDataWay = idx;
    },

    /***选中数据表格项 */
    onDataTableSelect(data) {
      if (data != this.selectDataTable) {
        this.selectDataTable = data;
        this.isTableOp = true;
      } else {
        this.selectDataTable = -1;
        this.isTableOp = false;
      }
    },
    /***获取属性表格 */
    loadAttrList() {
      this.originDataList = JSON.stringify(this.dataList);
      this.dataAttr = [];
      this.dataCalc = [];
      
      if (this.packageSet.dataOp) {
        this.dataAttr = this.packageSet.dataOp;
        for (var i=0;i<this.dataAttr.length;i++) {
          this.dataCalc.push({
            name: this.dataAttr[i].code,
            type: typeof this.dataList[0][key] == 'string' ? 'category' : 'value',
            calc: 'origin',
          });
        }
        this.packageSet.dataOp = null;
      }else{
        for (var key in this.dataList[0]) {
          this.dataAttr.push({ name: key, code: key, type: (typeof this.dataList[0][key])?(typeof this.dataList[0][key]):'string' });
          this.dataCalc.push({
            name: key,
            type: typeof this.dataList[0][key] == 'string' ? 'category' : 'value',
            calc: 'origin',
          });
        }
      }
      this.dataAttr = this.dataAttr.sort(function(a, b) {
        return CalcUtil.sortStr(a.code, b.code);
      });
      this.dataCalc = this.dataCalc.sort(function(a, b) {
        return CalcUtil.sortStr(a.name, b.name);
      });
      this.isTableCalc = false;
      //默认全选所有属性
      this.selectedAttrData = this.dataAttr;
      this.updateTableType();
      //设置pager
      this.pagerCurrent = 1;
      this.pagerLimit = 20;
      this.pagerTotal = Math.ceil(this.dataList.length / this.pagerLimit);
      this.getDataListShow();
    },
    setDataWay(way) {
      for (var i = 0; i < this.dataType.length; i++) {
        if (way == this.dataType[i].name) {
          this.selectDataWay = i;
          break;
        }
      }
    },
    //获取数据包
    loadDataSource(sourceId) {
      var that = this;
      DataSourceUtil.loadDataSource(sourceId, function(data) {
        if(data){
         //数据包类型(1:json,2:mysql,3:url)
         if (data.source_type == 1) {
          that.setDataWay('JSON');
        } else if (data.source_type == 2) {
          that.setDataWay('MySQL');
          that.mySQLSet = data.param;
        } else if (data.source_type == 3) {
          that.setDataWay('URL');
          that.urlSet = data.param;
        }
        that.packageSet.title = data.title;
        that.packageSet.detail = data.detail;
        that.packageSet.sourceId = data.source_id;
        that.packageSet.dataOp = data.data_op;
        if(data.dataList){
          that.dataList = data.dataList;
          that.loadAttrList();
        }else{
          that.alertTip = that.getLangText(that.label.loadDataFail);        
        that.isAlert = true;
        }
       
      }else{
        that.alertTip = that.getLangText(that.label.loadDataFail);        
        that.isAlert = true;    }   
      });
    },
    dealUrlParam(item){
      this.urlSet.url=item.path;
      var param=[];
      for(var i=0;i<item.param.length;i++){
        param.push({name:item.param[i].name,val:""});
      }
      this.urlSet.params=param;
    },
    resizeSource(){
      var body = document.getElementsByTagName('body')[0];
      this.listHeight = body.offsetHeight - 50 * 4 + 'px';
    },
    listenEvent(){
      this.app.$on("url-param",this.dealUrlParam);
    },
    offEvent(){
      this.app.$off("url-param",this.dealUrlParam);
    }
  },
  mounted() {
    this.listenEvent();
    var body = document.getElementsByTagName('body')[0];
    this.listHeight = body.offsetHeight - 50 * 4 + 'px';
    body.oncontextmenu = function() {
      return false;
    };
    var that=this;
    body.onresize=function(){
     that.resizeSource();
    }
    var address = window.location.hash;
    if (address.indexOf('sourceId') > 0) {
      address = address.split('=')[1];
      if (new String(address).length > 0) this.loadDataSource(address);
    }
  },
  beforeDestroy() {
    this.offEvent();
  },
};
